package cfca.seal.util;

import cfca.sadk.org.bouncycastle.asn1.x500.X500Name;
import cfca.sadk.x509.certificate.CFCAStyle;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.util.List;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class StringUtil
{
  public static synchronized String generateID()
  {
    UUID uuid = UUID.randomUUID();
    String id = uuid.toString().replaceAll("-", "");
    return id;
  }

  public static boolean isEmpty(String str)
  {
    if ((null == str) || ("".equals(str.trim()))) {
      return true;
    }
    return false;
  }

  public static boolean isNotEmpty(String str)
  {
    if ((str != null) && (!"".equals(str.trim()))) {
      return true;
    }
    return false;
  }

  public static String replace(String string, String replacement)
  {
    if (string != null) {
      return string.replaceAll(replacement, "");
    }
    return null;
  }

  public static String trim(String string)
  {
    if (isEmpty(string)) {
      return "";
    }
    return string.trim();
  }

  public static String getNodeText(String xmlString, String nodeName)
  {
    String beginName = "<" + nodeName + ">";
    String endName = "</" + nodeName + ">";
    int beginIndex = xmlString.indexOf(beginName);
    if (beginIndex == -1) {
      return "";
    }
    int endIndex = xmlString.indexOf(endName);
    if (endIndex == -1) {
      return "";
    }
    String nodeValue = xmlString.substring(beginIndex + beginName.length(), endIndex);
    return nodeValue;
  }

  public static void getNodesText(String xmlString, String nodeName, List<String> nodes)
  {
    String beginName = "<" + nodeName + ">";
    String endName = "</" + nodeName + ">";
    int beginIndex = xmlString.indexOf(beginName);
    if (beginIndex == -1) {
      return;
    }
    int endIndex = xmlString.indexOf(endName);
    if (endIndex == -1) {
      return;
    }
    String nodeValue = xmlString.substring(beginIndex + beginName.length(), endIndex);
    nodes.add(nodeValue);
    String subXml = xmlString.substring(endIndex + endName.length());
    getNodesText(subXml, nodeName, nodes);
  }

  public static String formatIssuerKey(String issuer)
  {
    return formatSubject(issuer).replaceAll(" ", "_").toLowerCase();
  }

  public static String formatSubject(String dn) {
    if (isNotEmpty(dn)) {
      dn = clearSpace(dn, ",");
      dn = clearSpace(dn, "=");
    }
    return dn;
  }

  public static String clearSpace(String target, String operator) {
    String[] items = target.split(operator);
    StringBuffer buffer = new StringBuffer();
    for (String item : items) {
      buffer.append(operator + item.trim());
    }

    return buffer.toString().substring(1);
  }

  public static String bytes2hex(byte[] bytes) {
    String b = "";
    StringBuffer buffer = new StringBuffer();
    for (int i = 0; i < bytes.length; i++) {
      b = Integer.toHexString(bytes[i] & 0xFF);
      if (b.length() == 1) {
        b = "0" + b;
      }
      buffer.append(b);
    }
    return buffer.toString().toUpperCase();
  }

  public static boolean checkValueInValid(String value) {
    String regEx = "[`~!@$%^&*+=|{}':;'\\[\\]<>/?~！@￥%……&*——+|{}【】‘；：”“’。，、？]";
    Pattern p = Pattern.compile(regEx);
    Matcher m = p.matcher(value);
    return m.find();
  }

  public static boolean checkValueInValid2(String value) {
    String regEx = "^[a-zA-Z0-9_]+$";
    Pattern p = Pattern.compile(regEx);
    Matcher m = p.matcher(value);
    return !m.find();
  }

  public static boolean checkPwdInValid(String value) {
    String regEx = "^[a-zA-Z0-9_]{6,12}$";
    Pattern p = Pattern.compile(regEx);
    Matcher m = p.matcher(value);
    return m.find();
  }

  boolean containsAny(String str, String searchChars) {
    if (str.contains(searchChars)) {
      return true;
    }
    return false;
  }

  public static boolean isNumeric(String str) {
    Pattern pattern = Pattern.compile("[0-9]*");
    return pattern.matcher(str).matches();
  }

  public static boolean checkNumber(String num, String type)
  {
    String eL = "";
    if (type.equals("0+"))
      eL = "^\\d+$";
    else if (type.equals("+"))
      eL = "^\\d*[1-9]\\d*$";
    else if (type.equals("-0"))
      eL = "^((-\\d+)|(0+))$";
    else if (type.equals("-"))
      eL = "^-\\d*[1-9]\\d*$";
    else
      eL = "^-?\\d+$";
    Pattern p = Pattern.compile(eL);
    Matcher m = p.matcher(num);
    boolean b = m.matches();
    return b;
  }

  public static boolean checkSubjectDN(String dn)
  {
    boolean isformatDn = false;
    if (isNotEmpty(dn)) {
      String[] dnParts = dn.split("=");
      if (dnParts.length > 2) {
        StringBuffer dnBuffer = new StringBuffer();
        for (int i = 0; i < dnParts.length; i++) {
          String tempPart = dnParts[i].trim();
          if (i != dnParts.length - 1)
            dnBuffer.append(tempPart).append("=");
          else {
            dnBuffer.append(tempPart);
          }
        }

        try
        {
          X500Name  subjectDN = new X500Name(CFCAStyle.INSTANCE, dnBuffer.toString());
        }
        catch (Exception e)
        {
//          X500Name subjectDN;
          isformatDn = false;
        }
        isformatDn = true;
      } else {
        isformatDn = false;
      }
    }
    return isformatDn;
  }

  public static byte[] singleLine2MultiLine(byte[] base64Data) {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    for (int i = 0; i < base64Data.length; i++) {
      if ((i != 0) && (i % 64 == 0)) {
        try {
          bos.write("\r\n".getBytes());
        } catch (IOException ex) {
          System.out.println(ex.toString());
        }
      }

      bos.write(base64Data[i]);
    }

    return bos.toByteArray();
  }
}